package websocket

import (
	"net/http"

	"github.com/gorilla/websocket"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

// 确保WebSocketServer实现了BroadcastService接口
var _ BroadcastService = (*WebSocketServer)(nil)

// 确保WebSocketServer实现了GameService接口
var _ GameService = (*WebSocketServer)(nil)

// 确保WebSocketServer实现了MessageService接口
var _ MessageService = (*WebSocketServer)(nil)

// 确保OnlineStatusManager实现了OnlineStatusManagerInterface接口
var _ OnlineStatusManagerInterface = (*OnlineStatusManager)(nil)

// 确保WebSocketServer实现了OnlineStatusManagerGetter接口
var _ OnlineStatusManagerGetter = (*WebSocketServer)(nil)

// 这里可以添加其他必要的方法或函数

var defaultServer *WebSocketServer

// GetDefaultServer 获取默认的WebSocket服务器实例
func GetDefaultServer() *WebSocketServer {
	return defaultServer
}

// SetDefaultServer 设置默认的WebSocket服务器实例
func SetDefaultServer(server *WebSocketServer) {
	defaultServer = server
}

// NewWebSocketServerInstance 创建一个新的WebSocket服务器实例
func NewWebSocketServerInstance(addr string) *WebSocketServer {
	server := &WebSocketServer{
		rooms:           make(map[string]*Room),
		gameRooms:       make(map[string]*GameRoom),
		roomListClients: make(map[string]*Client),
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		},
		db: nil, // 需要在使用前设置
	}

	// 初始化在线状态管理器
	server.onlineStatusManager = NewOnlineStatusManager(server)

	return server
}

// SetHandler 设置HTTP处理器
func (s *WebSocketServer) SetHandler(handler http.Handler) {
	// 这里简化处理，实际项目中可能需要更复杂的逻辑
}

// SetDB 设置数据库连接
func (s *WebSocketServer) SetDB(db *gorm.DB) {
	s.db = db
}

// ServeHTTP 实现http.Handler接口
func (s *WebSocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 处理WebSocket连接
	if r.URL.Path == "/ws" {
		// 从查询参数中获取必要的参数，支持多种参数名格式
		userID := r.URL.Query().Get("userId")
		if userID == "" {
			userID = r.URL.Query().Get("user_id")
		}

		roomID := r.URL.Query().Get("roomId")
		if roomID == "" {
			roomID = r.URL.Query().Get("room_id")
		}

		userName := r.URL.Query().Get("userName")
		if userName == "" {
			userName = r.URL.Query().Get("user_name")
		}

		// 如果没有提供用户ID，返回错误信息
		if userID == "" {
			logx.Errorf("[ServeHTTP] 缺少用户ID参数")
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(`{"error":"缺少用户ID参数","message":"请提供userId或user_id参数"}`))
			return
		}

		// 如果没有提供用户名，使用默认值
		if userName == "" {
			userName = "用户" + userID
		}

		logx.Infof("[ServeHTTP] 处理WebSocket连接请求: userID=%s, roomID=%s, userName=%s", userID, roomID, userName)
		s.ServeWS(w, r, userID, roomID, userName)
		return
	}

	// 否则返回404
	http.Error(w, "Not found", http.StatusNotFound)
}

// BroadcastToUser 向指定用户广播消息
func (s *WebSocketServer) BroadcastToUser(userID string, msg Message) bool {
	// 查找用户的WebSocket连接
	s.roomsMu.RLock()
	for _, room := range s.rooms {
		if client, exists := room.Clients[userID]; exists {
			select {
			case client.Send <- msg.ToJSON():
				s.roomsMu.RUnlock()
				return true
			default:
				// 通道已满，跳过此客户端
			}
		}
	}
	s.roomsMu.RUnlock()

	// 也检查游戏房间
	s.gameRoomsMu.RLock()
	for _, gameRoom := range s.gameRooms {
		if client, exists := gameRoom.Clients[userID]; exists {
			select {
			case client.Send <- msg.ToJSON():
				s.gameRoomsMu.RUnlock()
				return true
			default:
				// 通道已满，跳过此客户端
			}
		}
	}
	s.gameRoomsMu.RUnlock()

	return false
}

// BroadcastToRoom 广播消息到房间
func (s *WebSocketServer) BroadcastToRoom(room *Room, msg Message) {
	room.Broadcast(msg)
}

// BroadcastToGameRoom 广播消息到游戏房间
func (s *WebSocketServer) BroadcastToGameRoom(room *GameRoom, msg Message) {
	room.Broadcast(msg)
}

// StartGame 开始游戏
func (s *WebSocketServer) StartGame(room *GameRoom) {
	// 游戏开始逻辑将在消息处理器中实现
}

// StopGame 停止游戏
func (s *WebSocketServer) StopGame(room *GameRoom) {
	// 游戏停止逻辑将在消息处理器中实现
}

// HandleGameOp 处理游戏操作
func (s *WebSocketServer) HandleGameOp(room *GameRoom, userID string, op GameOp) {
	// 游戏操作处理逻辑将在消息处理器中实现
}

// ProcessMessage 处理消息
func (s *WebSocketServer) ProcessMessage(client *Client, message Message, context interface{}) error {
	// 获取默认消息处理器
	processor := CreateStandardMessageProcessor()
	if room, ok := context.(*Room); ok {
		return processor.ProcessMessage(client, message, room)
	}
	return nil
}

// GetOnlineStatusManager 获取在线状态管理器
func (s *WebSocketServer) GetOnlineStatusManager() *OnlineStatusManager {
	return s.onlineStatusManager
}

// CreateStandardMessageProcessor 创建标准消息处理器
func (s *WebSocketServer) CreateStandardMessageProcessor() *MessageProcessor {
	return CreateStandardMessageProcessor()
}

// TriggerTravelNotice 触发虚拟旅行通知
func (s *WebSocketServer) TriggerTravelNotice(userID string, notice string) bool {
	if s.onlineStatusManager != nil {
		return s.onlineStatusManager.SendTravelNotice(userID, notice)
	}
	return false
}

// BroadcastTravelNotice 广播虚拟旅行通知给所有在线用户
func (s *WebSocketServer) BroadcastTravelNotice(notice string) {
	if s.onlineStatusManager == nil {
		return
	}

	// 获取所有在线用户
	users := s.onlineStatusManager.GetAllUsers()
	for _, user := range users {
		if user.IsOnline {
			s.onlineStatusManager.SendTravelNotice(user.UserID, notice)
		}
	}
}
